<?php 
namespace Admin\Controller;

class BlogController extends BaseController{
    public function index(){
        
        // 获取博客栏目
        $cats = M('cat')->field(array('cat_id','cat_name'))->select();
        
        // 获取博客数据
        $blogs = M('blog')->order('id desc')->select();
        
        // 传递数据
        $this->assign('blogs',$blogs);
        $this->assign('cats',$cats);
        
        $this->display('blog');
    }
    
    // 添加数据
    public function add(){
        $this->assign('time',time());
        if (IS_POST){
            $data = I('post.');
            $data['content'] = $_POST['content'];
            $data['time'] = strtotime($_POST['time']);
            unset($data['id']);
            
            // 验证表单数据
            $cat = M('blog');
            $rule = array(
                array('title','require','博客标题不能为空'),
                array('cat_id','0','必须选择栏目',1,'notequal'),
                array('time','require','必须选择栏目'),
            );
            if (!$cat->validate($rule)->create()){
                
                $this->error($cat->getError(),U('add'));die;
            }
            
            if (I('post.id')==0){
                // 添加数据
                $res = $cat->data($data)->add();
            }else {
                $res = $cat->where('id='.I('post.id'))->save($data);
            }
            
            if ($res){
                $this->show('<script>var index = parent.layer.getFrameIndex(window.name);parent.location.reload();parent.layer.close(index);</script>');
            }else {
                $this->error('添加数据失败',U('add',array('id'=>I('post.id'))));
            }
        }elseif (!empty(I('get.id'))){
            

            // 获取博客数据
            $blog = M('blog');
            $res = $blog->where('id='.I('get.id'))->find();
            
            // 获取博客栏目
            $cats = M('cat')->field(array('cat_id','cat_name'))->select();
            
            $this->assign('cats',$cats);
            $this->assign('blog',$res);
            
            $this->display('Blog/blog_add');
        }else {
            // 获取博客栏目
            $cats = M('cat')->field(array('cat_id','cat_name'))->select();
            
            $this->assign('cats',$cats);
            
            $this->display('Blog/blog_add');
        }
    }
    
}

?>